<template>
  <el-dialog
    :model-value="visible"
    title="选择目标文件夹"
    width="500px"
    :close-on-click-modal="false"
    @update:model-value="(value: boolean) => emit('update:visible', value)"
    @close="handleClose"
    align-center
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon">
          <el-icon :size="24"><FolderOpened /></el-icon>
        </div>
        <div class="header-title">
          <h3>选择目标文件夹</h3>
          <p class="header-subtitle">选择要将文件移动到的文件夹</p>
        </div>
      </div>
    </template>

    <div class="dialog-body" v-loading="loading">
      <el-tree-select
        v-model="selectedFolderId"
        :data="filteredFolderTree"
        :props="{ label: 'name', value: 'id', children: 'children' }"
        placeholder="选择目标文件夹（留空则移动到根目录）"
        clearable
        check-strictly
        :render-after-expand="false"
        size="large"
        class="folder-select"
        style="width: 100%"
      >
        <template #default="{ data }">
          <span>
            <el-icon style="margin-right: 6px;"><Folder /></el-icon>
            {{ data.name }}
            <span v-if="data.file_count > 0" class="file-count">({{ data.file_count }})</span>
          </span>
        </template>
      </el-tree-select>
      
      <div v-if="currentFolderId && currentFolderId === selectedFolderId" class="warning-tip">
        <el-icon><Warning /></el-icon>
        <span>目标文件夹与当前文件夹相同，无需移动</span>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleClose">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="handleConfirm" 
          :disabled="currentFolderId === selectedFolderId"
          :loading="moving"
        >
          <el-icon v-if="!moving"><Check /></el-icon>
          确认移动
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Folder, FolderOpened, Check, Close, Warning } from '@element-plus/icons-vue'
import { getKnowledgeFolders, type KnowledgeFolder } from '@/api/knowledge'
import { ResponseParser } from '@/utils/responseParser'

interface Props {
  visible: boolean
  currentFolderId?: string
  excludeFolderId?: string // 排除的文件夹ID（用于移动文件夹时，不能移动到自身或子文件夹）
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'confirm', folderId: string | undefined): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  currentFolderId: undefined,
  excludeFolderId: undefined
})

const emit = defineEmits<Emits>()

const loading = ref(false)
const moving = ref(false)
const folderTree = ref<KnowledgeFolder[]>([])
const selectedFolderId = ref<string | undefined>(undefined)

// 加载文件夹树
const loadFolderTree = async () => {
  try {
    loading.value = true
    const response = await getKnowledgeFolders({ tree: true })
    const parsed = ResponseParser.parseResponse<KnowledgeFolder[]>(response)
    
    if (parsed.success && parsed.data && Array.isArray(parsed.data)) {
      folderTree.value = parsed.data
    } else {
      folderTree.value = []
    }
  } catch (error) {
    console.error('加载文件夹树失败:', error)
    ElMessage.error('加载文件夹树失败')
    folderTree.value = []
  } finally {
    loading.value = false
  }
}

// 过滤文件夹树（排除指定文件夹及其子文件夹）
const filterFolderTree = (folders: KnowledgeFolder[], excludeId?: string): KnowledgeFolder[] => {
  if (!excludeId) return folders
  
  return folders
    .filter(folder => folder.id !== excludeId)
    .map(folder => ({
      ...folder,
      children: folder.children ? filterFolderTree(folder.children, excludeId) : undefined
    }))
}

// 计算过滤后的文件夹树
const filteredFolderTree = computed(() => {
  return filterFolderTree(folderTree.value, props.excludeFolderId)
})

// 确认移动
const handleConfirm = () => {
  if (props.currentFolderId === selectedFolderId.value) {
    ElMessage.warning('目标文件夹与当前文件夹相同，无需移动')
    return
  }
  
  emit('confirm', selectedFolderId.value)
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  selectedFolderId.value = undefined
}

// 监听可见性变化
watch(() => props.visible, (visible) => {
  if (visible) {
    selectedFolderId.value = props.currentFolderId
    loadFolderTree()
  } else {
    selectedFolderId.value = undefined
  }
})
</script>

<style scoped lang="scss">
.dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;

  .header-icon {
    color: var(--el-color-primary);
  }

  .header-title {
    flex: 1;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    .header-subtitle {
      margin: 4px 0 0 0;
      font-size: 14px;
      color: #909399;
    }
  }
}

.dialog-body {
  padding: 20px 0;
  min-height: 200px;

  .folder-select {
    :deep(.el-select) {
      width: 100%;
    }
  }

  .file-count {
    color: #909399;
    font-size: 12px;
    margin-left: 4px;
  }

  .warning-tip {
    margin-top: 16px;
    padding: 12px;
    background: var(--el-color-warning-light-9);
    border: 1px solid var(--el-color-warning-light-7);
    border-radius: 4px;
    color: var(--el-color-warning-dark-2);
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;

    .el-icon {
      font-size: 16px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
